package com.isoft.service.impl;

import com.isoft.entity.DfmeDepeEntity;
import com.isoft.mapper.DfmeDepeMapper;
import com.isoft.service.DfmeDepeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeDepeServiceImpl implements DfmeDepeService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeDepeServiceImpl.class);

    @Autowired
    private DfmeDepeMapper dfmeDepeMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-DEPE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeDepeEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeDepeEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeDepeEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-DEPE XML structure");
            }

            // 验证并修正STATUS值
            if (entity.getDflt().getStatus() != null &&
                    !entity.getDflt().getStatus().matches("NORMAL|DELAYED|CANCELLED|BOARDING|DEPARTED|ALTERNATE|RETURNED|BOARDING_COMPLETED")) {
                logger.warn("Invalid flight status: {}, defaulting to DEPARTED", entity.getDflt().getStatus());
                entity.getDflt().setStatus("DEPARTED");
            }

            processFlightData(entity);

            return "DFME-DEPE data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-DEPE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-DEPE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeDepeEntity entity) {
        try {
            dfmeDepeMapper.insertMeta(entity);
            dfmeDepeMapper.insertOrUpdateFlightBase(entity);

            // 尝试插入航线信息，如果失败则记录警告
            try {
                dfmeDepeMapper.insertFlightRoute(entity);
            } catch (Exception e) {
                logger.warn("Failed to insert flight route for flight ID: {}. Error: {}",
                        entity.getDflt().getFlightId(), e.getMessage());
            }

            logger.info("Processed departure data for flight ID: {}", entity.getDflt().getFlightId());
        } catch (Exception e) {
            logger.error("Failed to process flight data for flight ID: {}", entity.getDflt().getFlightId(), e);
            throw e;
        }
    }
}